//
//  TMTVInfoVC.m
//  TMBD Movie App
//
//  Created by zhangkai on 2023/4/11.
//

#import "TMTVInfoVC.h"
#import <Masonry.h>
#import "TMTVOneCell.h"
#import "TMTVTwoCell.h"
#import "movieInfo-Swift.h"
#import "MoiveinfoModel.h"
#import "TMMovieModel.h"
#import "TMMovieInfoModel.h"
#import "TMAllMovieListView.h"
//#import <VKFoundation/VKFoundation.h>
@interface TMTVInfoVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(strong,nonatomic)UICollectionView *mainCollectionView;


@property(strong,nonatomic)TMMovieInfoModel *model;

@property(strong,nonatomic)TMTVInfoPlayView *playView;


@property(strong,nonatomic)UIButton *shawView;
@property(strong,nonatomic)TMAllMovieListView *allView;
@end

@implementation TMTVInfoVC

- (void)configTopView{
    
    
//https://autoeq.top/mov/a00d4e8d2c0e9f0a8bb202f951fb4204fix5/a00d4e8d2c0e9f0a8bb202f951fb4204fix5.m3u8?expire=1682874363&auth=102af7c16f4cec35c1f01c0d08b5bc64a1019077689ef7179fdc1bd14f741f53&xaid=AEBA122D-1EB8-4893-B09F-B6A146384041&p1=35140,265,169.150.221.195
//
    
    UIView *topView = [UIView new];
    topView.frame = CGRectMake(0, -100, kScreenW, 100);
    topView.backgroundColor = [UIColor blackColor];
//    self.mainTableView.tableHeaderView = topView;
    [self.mainCollectionView addSubview:topView];
    

    
    
//    VKVikiVideoPlayer *player = [[VKVikiVideoPlayer alloc] initWithVideoPlayerView:[[VKVikiVideoPlayer alloc] init]];
//    self.player.delegate = self;
//    [self.view addSubview:self.player]
    
    UILabel *nameLabel = ({
        UILabel *nameLabel = [UILabel new];
        nameLabel.text = @"the fallout";
        nameLabel.textColor = [UIColor whiteColor];
        nameLabel.font = [UIFont systemFontOfSize:24 weight:UIFontWeightMedium];
        nameLabel;
    });
    [topView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView).offset(15);
        make.left.equalTo(topView).offset(15);
    }];
    
    UIImageView *xingIcon = ({
        UIImageView *icon = [UIImageView new];
        icon.image = [UIImage imageNamed:@"star"];
        icon;
    });
    [topView addSubview:xingIcon];
    [xingIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nameLabel);
        make.right.equalTo(topView).offset(-20);
    }];
    
    UIImageView *shareIcon = ({
        UIImageView *icon = [UIImageView new];
        icon.image = [UIImage imageNamed:@"star"];
        icon;
    });
    [topView addSubview:shareIcon];
    [shareIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(nameLabel);
        make.right.equalTo(xingIcon.mas_left).offset(-20);
    }];
    
    UIButton *fenBtn = ({
        UIButton *btn = [UIButton new];
        [btn setTitle:@"IMDB：9.8" forState:UIControlStateNormal];
        btn.backgroundColor = Kcolor(255, 109, 109, 0.1);
        [btn setTitleColor:Kcolor(255, 109, 109, 1) forState:UIControlStateNormal];
        btn.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        btn.userInteractionEnabled = NO;
        btn;
    });
    
    [topView addSubview:fenBtn];
    [fenBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(topView).offset(15);
        make.bottom.equalTo(topView).offset(-20);
    }];
    
    UIButton *timeBtn = ({
        UIButton *btn = [UIButton new];
        [btn setTitle:@"2022-01-28" forState:UIControlStateNormal];
        btn.backgroundColor = Kcolor(39, 58, 228, 0.1);
        [btn setTitleColor:Kcolor(39, 58, 228, 1) forState:UIControlStateNormal];
        btn.contentEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        btn.userInteractionEnabled = NO;
        btn;
    });
    
    [topView addSubview:timeBtn];
    [timeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(fenBtn.mas_right).offset(15);
        make.bottom.equalTo(topView).offset(-20);
    }];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:13/255.0 green:19/255.0 blue:35/255.0 alpha:1];
    
    UIView *topView = [UIView new];
    topView.backgroundColor = [UIColor purpleColor];
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(211);
    }];
    
//    TMTVInfoPlayView TMTVInfoPlayVC
    
    TMTVInfoPlayView *playView = [TMTVInfoPlayView new];
//    [topView addSubview:playView];
//    playView.frame = CGRectMake(0, 0, kScreenW, 211);
    [self addChildViewController:playView];
    [topView addSubview:playView.view];
    playView.view.frame = CGRectMake(0, 0, kScreenW, 211);
    [playView didMoveToParentViewController:self];
    self.playView = playView;
    
    

   
    UICollectionViewFlowLayout *fl = [UICollectionViewFlowLayout new];
    self.mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:fl];
    [self.view addSubview:self.mainCollectionView];
    self.mainCollectionView.delegate = self;
    self.mainCollectionView.dataSource = self;
    [self.mainCollectionView registerClass:[TMTVOneCell class] forCellWithReuseIdentifier:@"TMTVOneCell"];
    [self.mainCollectionView registerClass:[TMTVTwoCell class] forCellWithReuseIdentifier:@"TMTVTwoCell"];

    self.mainCollectionView.backgroundColor = [UIColor colorWithRed:13/255.0 green:19/255.0 blue:35/255.0 alpha:1];
    self.mainCollectionView.contentInset = UIEdgeInsetsMake(110, 0, 0, 0);
    
    [self.mainCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(topView.mas_bottom);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
    }];

    [self configTopView];
    
    [self getInfo];

}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    

    if(section == 0){
        return 1;
    }else{
        return self.model.subsectionArr.count;
    }
    

}

- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if(indexPath.section == 0){
        TMTVOneCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TMTVOneCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor yellowColor];
        return cell;
    }else{
        TMTVTwoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TMTVTwoCell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor yellowColor];
        return cell;
    }

//    cell.backgroundColor = [UIColor yellowColor];
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;{
    if(indexPath.section == 0){
        return CGSizeMake(kScreenW, 100);
    }else{
        return CGSizeMake((kScreenW-50)/2, 100);
    }
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;{
    return  UIEdgeInsetsMake(10, 15, 10, 15);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;{
    return 8;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;{
    return 8;
}

- (void)getInfo{
    
    NSTimeInterval timein = [[NSDate date] timeIntervalSince1970];
    int intTime = (int)timein;
    NSString *timeStr = [NSString stringWithFormat:@"%d",intTime];
    
    NSString *noStr = [[TMDeviceInfo deviceNo] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    NSString *uavalie = [[TMNetworkManage defaultManager] getencry:[NSString stringWithFormat:@"%@%@",noStr,timeStr]];
    NSString *sigs = [[TMNetworkManage defaultManager] getsigencry:uavalie];
    
    
    
//    let devNo = DeviceInfo.deviceNo.replacingOccurrences(of: "-", with: "")
//    let ueValue = EncryManager.sharedInstance.loadDevEncry(value: devNo+time)
//    let sig = EncryManager.sharedInstance.loadSigEncryManager(value:ueValue)
    
    if(self.idstr.length == 0){
        return;
    }
    
    NSDictionary *dic = @{
        @"id":self.idstr,
        @"reg_id":@" "
    };
    //
    
    [[TMNetworkManage defaultManager] MVWithApiName:@"202/" parameters:dic success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        
        TMMovieModel *model = [TMMovieModel mj_objectWithKeyValues:responseObject];
        if(model.state == 200){
            NSString *time = [model.allDic objectForKey:@"pub_date"];
            NSString *tagstr = [model.allDic objectForKey:@"tags"];
            NSMutableArray *tags = [[tagstr componentsSeparatedByString:@","] mutableCopy];
            [tags addObject:time];
            
            TMMovieInfoModel *infoModel = [TMMovieInfoModel mj_objectWithKeyValues:model.allDic];
            infoModel.curtags = tags.copy;
            
            NSMutableArray *newlistArr = @[].mutableCopy;
            for (NSDictionary *dic1 in model.categArr) {
                if([[dic1 objectForKey:@"name"] length] > 0){
                    [newlistArr addObject:dic1];
                }
            }
            
            infoModel.categoryArr = newlistArr.copy;
            infoModel.sectionArr = [model.allDic objectForKey:@"155"];
            self.model = infoModel;
            if(infoModel.sectionArr.count > 0){
                NSDictionary *dic = infoModel.sectionArr[0];
                id tempID = [dic objectForKey:@"id"];
                if([tempID isKindOfClass:[NSNumber class]]){
                    NSNumber *idstr = (NSNumber *)tempID;
                    [self getsectionInfo:idstr.stringValue];
                }else if([tempID isKindOfClass:[NSString class]]){
                    NSString *idstr = (NSString *)tempID;
                    [self getsectionInfo:idstr];
                }
                
            }
            

            
//            if(infoModel.playUrl.length > 0){
//                [self.playView setupPlayerResourceWithPlaystr:infoModel.playUrl];
//            }
//
              
            
        }
        
                
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        
    }];
    
    
    
}

- (void)getsectionInfo:(NSString *)idstr{
    
    
    
    NSTimeInterval timein = [[NSDate date] timeIntervalSince1970];
    int intTime = (int)timein;
    NSString *timeStr = [NSString stringWithFormat:@"%d",intTime];
    
    NSString *noStr = [[TMDeviceInfo deviceNo] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    NSString *uavalie = [[TMNetworkManage defaultManager] getencry:[NSString stringWithFormat:@"%@%@",noStr,timeStr]];
    NSString *sigs = [[TMNetworkManage defaultManager] getsigencry:uavalie];
    
    
    
//    let devNo = DeviceInfo.deviceNo.replacingOccurrences(of: "-", with: "")
//    let ueValue = EncryManager.sharedInstance.loadDevEncry(value: devNo+time)
//    let sig = EncryManager.sharedInstance.loadSigEncryManager(value:ueValue)
    
    if(self.idstr.length == 0){
        return;
    }
    
    NSDictionary *dic = @{
        @"id":self.idstr,
        @"api_ver":@"1",
        @"reg_id":@" ",
        @"unixtime":timeStr,
        @"sig":sigs
        
    };
    [[TMNetworkManage defaultManager] MVWithApiName:@"203/" parameters:dic success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        
        TMMovieModel *model = [TMMovieModel mj_objectWithKeyValues:responseObject];
        if(model.state == 200){
           
            NSArray *arr = [model.allDic objectForKey:@"174"];
            self.model.subsectionArr = arr.copy;
            if(self.model.subsectionArr.count > 0){
                
                NSDictionary *dic = self.model.subsectionArr[0];
                id tempID = [dic objectForKey:@"id"];
                if([tempID isKindOfClass:[NSNumber class]]){
                    NSNumber *idstr = (NSNumber *)tempID;
                    [self getsectionPlayInfo:idstr.stringValue];
                }else if([tempID isKindOfClass:[NSString class]]){
                    NSString *idstr = (NSString *)tempID;
                    [self getsectionPlayInfo:idstr];
                }
            }
           
            [PlayerManage defaultManager].currentMovie = self.model;
            [self.mainCollectionView reloadData];
   
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        
    }];
    
    
    
}

- (void)getsectionPlayInfo:(NSString *)idstr{
    
    
    
    NSTimeInterval timein = [[NSDate date] timeIntervalSince1970];
    int intTime = (int)timein;
    NSString *timeStr = [NSString stringWithFormat:@"%d",intTime];
    
    NSString *noStr = [[TMDeviceInfo deviceNo] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    NSString *uavalie = [[TMNetworkManage defaultManager] getencry:[NSString stringWithFormat:@"%@%@",noStr,timeStr]];
    NSString *sigs = [[TMNetworkManage defaultManager] getsigencry:uavalie];
    
    
    
//    let devNo = DeviceInfo.deviceNo.replacingOccurrences(of: "-", with: "")
//    let ueValue = EncryManager.sharedInstance.loadDevEncry(value: devNo+time)
//    let sig = EncryManager.sharedInstance.loadSigEncryManager(value:ueValue)
    
    if(self.idstr.length == 0){
        return;
    }
    
    NSDictionary *dic = @{
        @"id":self.idstr,
        @"api_ver":@"1",
        @"reg_id":@" ",
        @"unixtime":timeStr,
        @"sig":sigs
        
    };
    [[TMNetworkManage defaultManager] MVWithApiName:@"151/" parameters:dic success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        
        TMMovieModel *model = [TMMovieModel mj_objectWithKeyValues:responseObject];
        if(model.state == 200){
            
            
            [PlayerManage defaultManager].currentMovie.playUrl = [model.allDic objectForKey:@"235"];
            if([PlayerManage defaultManager].currentMovie.playUrl.length > 0){
                
                [self.playView setupPlayerResourceWithPlaystr:[PlayerManage defaultManager].currentMovie.playUrl];
                return;
            }
            
            [PlayerManage defaultManager].currentMovie.playUrl = [[model.allDic objectForKey:@"hd"] objectForKey:@"link"];
            if([PlayerManage defaultManager].currentMovie.playUrl.length > 0){
                
                [self.playView setupPlayerResourceWithPlaystr:[PlayerManage defaultManager].currentMovie.playUrl];
                return;
            }
            
            [PlayerManage defaultManager].currentMovie.playUrl = [[model.allDic objectForKey:@"sd"] objectForKey:@"link"];
            if([PlayerManage defaultManager].currentMovie.playUrl.length > 0){
                
                [self.playView setupPlayerResourceWithPlaystr:[PlayerManage defaultManager].currentMovie.playUrl];
                return;
            }
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        
    }];
    
    
    
}


@end
